import { request } from "../../request/index.js";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

// pages/user_info/index.js
Page({
  data: {
    avatar: '',
    userName: '',
    contactAddress: '',
    phoneNumber: '',
    isRe: true,
    // 判断是否有更换头像
    isChange: false
  },

  onLoad () {
    this.getUserInfo()
  },

  // 上传图片
  handleChooseImg() {
    // 2 调用小程序内置的选择图片api
    wx.chooseImage({
      // 同时选中的图片的数量
      count: 1,
      // 图片的格式  原图  压缩
      sizeType: ['original', 'compressed'],
      // 图片的来源  相册  照相机
      sourceType: ['album', 'camera'],
      success: (result) => {
        if (result.tempFiles[0].size > 1048576) {
          wx.showToast({
            title: '图片太大',
            icon: 'error'
          });
        } else {
          this.setData({
            // 图片数组 进行拼接 
            avatar: result.tempFilePaths[0],
            isChange: true
          })
        }
        
      }
    })
  },

  // 提交表单
  async formSubmit (e) {
    const { password, password_sure } = e.detail.value
    if (password_sure != password) {
      wx.showToast({
        title: '密码不一致',
        icon: 'error',
        duration: 1500
      });
      return
    } else {
      wx.showModal({
        title: '确定提交表单？',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: async (result) => {

          let avatar = this.data.avatar

          if (avatar && avatar.trim().length != 0 && this.data.isChange) {
            console.log("上传图片")
            wx.showLoading({
              title: "加载中",
              mask: true
            });
            avatar = await new Promise((resolve,reject)=>{
              wx.uploadFile({
                url: 'http://1.14.202.218:7777/fileoss',
                filePath: avatar,
                name: 'file',
                success:(res)=>{
                  resolve(JSON.parse(res.data).data);
                },
                fail:(err)=>{
                  reject(err);
                },
                complete:()=>{
                  wx.hideLoading();
                }
              })
            })
          } else {
            avatar = null
          }

          let data = {
            ...e.detail.value,
            avatar
          }
          delete data['password_sure']

          console.log(data)
          const res = await request({
            url: '/user/update',
            method: 'post',
            header: {
              'content-type':'application/json',
              token: wx.getStorageSync('token')
            },
            data
          })
          console.log(res)
          if (res.resultTypeCode == 200) {
            wx.showToast({
              title: '更新成功',
              icon: 'success',
              duration: 1500,
            })
            this.setData ({
              isRe: false
            })
            this.getUserInfo ()
          } else {
            wx.showToast({
              title: '更新失败',
              icon: 'error',
              duration: 1500,
            })
          }
        }
      });
    }
  },

  // 请求用户数据
  async getUserInfo () {
    const res = await request({
      url: '/user/queryUserByToken',
      method: 'post',
      header: {
        'content-type':'application/json',
        token: wx.getStorageSync('token')
      },
      data: wx.getStorageSync('token')
    })
    if (res.resultTypeCode == 200) {
      const { userName, avatar, phoneNumber, contactAddress } = res.data 
      this.setData ({
        userName,
        avatar,
        contactAddress,
        phoneNumber,
        isRe: true
      })
    }
  }
})